/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  MainZhiShiActivity.java   
 * @Package com.jiyi.activity.main   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-6-23 上午10:02:35   
 * @version V1.0     
 */
package com.jiyi.activity.owner;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiyi.activity.new_maintenance.JoinMemberReadActivity;
import com.jiyi.activity.new_maintenance.MaintenanceTaskDetailActivity;
import com.jiyi.adapter.DividerItemDecoration;
import com.jiyi.adapter.recyclerview.MultiItemTypeAdapter;
import com.jiyi.adapter.recyclerview.base.ItemViewDelegate;
import com.jiyi.adapter.recyclerview.base.ViewHolder;
import com.jiyi.adapter.recyclerview.wrapper.EmptyWrapper;
import com.jiyi.bean.main.NewsListJson.NewsBean;
import com.jiyi.bean.maintenance.Task;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.event.MaintenanceTaskListEvent;
import com.jiyi.inteface.WebApi;
import com.jiyi.widget.picshow.ImagePagerActivity;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @ClassName: MainZhiShiActivity
 * @Description:TODO(这里用一句话描述这个类的作用)
 * @author: HYM
 * @date: 2017-6-23 上午10:02:35
 * 
 */
public class OwnerAllMaintenanceTaskFragment extends Fragment implements
OnRefreshListener{

	List<NewsBean> newsList = new ArrayList<NewsBean>();
	LayoutInflater inflater;

	@BindView(R.id.mainList)
	RecyclerView mListView;
	@BindView(R.id.refreshLayout)
	SwipeRefreshLayout refreshLayout;
	private List<Task> mTasks = new ArrayList<Task>();
	EmptyWrapper adapter;
	ViewGroup container;
	int type;

	Dialog dialog;

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, Bundle savedInstanceState) {
		View view = inflater
				.inflate(R.layout.fragment_all_wx_task, null, false);
		ButterKnife.bind(this, view);
		this.inflater = inflater;
		this.container = container;
		init();
		return view;
	}

	private void init() {
		getIntentData();
		getData();
		setAdapter();
	}

	/**
	 * @author: HYM
	 * @Title: getIntentData
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-8-30
	 */
	private void getIntentData() {
		type = getArguments().getInt("type", 0);
	}

	@Override
	public void onRefresh() {
		getData();
	}
	
	private void getData() {

		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("type", (type+1) + "");
		VolleyRequest.StringRequestPost(getContext(),
				WebApi.OWNER_MAINTENANCE_TASK_LIST, "", params,
				new StringInterface(getContext()) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								List<Task> tasks = new Gson().fromJson(data,
										new TypeToken<List<Task>>() {
										}.getType());
								mTasks.clear();
								mTasks.addAll(tasks);
								adapter.notifyDataSetChanged();
							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							refreshLayout.setRefreshing(false);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						refreshLayout.setRefreshing(false);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

	private void setAdapter() {
		// 设置refreshLayout的监听
		refreshLayout.setColorSchemeColors(Color.RED, Color.YELLOW, Color.BLUE,
				Color.GREEN);
		refreshLayout.setOnRefreshListener(this);

		mListView.setLayoutManager(new LinearLayoutManager(getContext()));
		mListView.addItemDecoration(new DividerItemDecoration(getContext(),
				DividerItemDecoration.VERTICAL_LIST, getResources()
						.getDrawable(R.drawable.drvice_10)));

		MultiItemTypeAdapter multiItemTypeAdapter = new MultiItemTypeAdapter(
				getContext(), mTasks);
		multiItemTypeAdapter.addItemViewDelegate(new SignDelagate());
		multiItemTypeAdapter.addItemViewDelegate(new DetectDelagate());
		multiItemTypeAdapter.addItemViewDelegate(new FinishDelagate());

		adapter = new EmptyWrapper(multiItemTypeAdapter);

		View emptyView = inflater.inflate(R.layout.empty_view_text_and_image,
				container, false);
		ImageView ivEmptyTip = (ImageView) emptyView
				.findViewById(R.id.ivEmptyTip);
		TextView tvEmptyTip = (TextView) emptyView
				.findViewById(R.id.tvEmptyTip);
		ivEmptyTip.setImageResource(R.mipmap.tip_empty_huodong);
		tvEmptyTip.setText(R.string.NO_DATA);
		adapter.setEmptyView(emptyView);

		mListView.setAdapter(adapter);
		adapter.notifyDataSetChanged();
	}

	public class SignDelagate implements ItemViewDelegate<Task> {

		@Override
		public int getItemViewLayoutId() {
			return R.layout.item_maintenance_mytask_sign;
		}

		@Override
		public boolean isForViewType(Task item, int position) {
			return item.getStatus() == 1;
		}

		@Override
		public void convert(ViewHolder holder, final Task task,
				final int position) {
			holder.setText(R.id.tvUnitTip, "维保单位：");
			holder.setText(R.id.tvCompany, task.getWb_company_name());
			holder.setText(R.id.tvDate, task.getTask_time());
			holder.setText(R.id.tvInfo, task.getParticipants());
			holder.setText(R.id.tvUsername, task.getTask_user_name());
			holder.setText(R.id.tvAssginTip, "派发对象：");
			holder.setVisible(R.id.tvSign, false);
		}
	}

	public class DetectDelagate implements ItemViewDelegate<Task> {

		@Override
		public int getItemViewLayoutId() {
			return R.layout.item_maintenance_mytask_detect;
		}

		@Override
		public boolean isForViewType(Task item, int position) {
			return item.getStatus() == 2;
		}

		@Override
		public void convert(final ViewHolder holder, final Task task,
				final int position) {

			holder.setText(R.id.tvUnitTip, "维保单位：");
			holder.setText(R.id.tvCompany, task.getWb_company_name());
			holder.setText(R.id.tvDate, task.getTask_time());
			holder.setText(R.id.tvUsername, task.getTask_user_name());
			holder.setText(R.id.tvAssginTip, "派发对象：");
			holder.setText(R.id.tvInfo, task.getParticipants());
			holder.setOnClickListener(R.id.tvWatchSignPic,
					new OnClickListener() {

						@Override
						public void onClick(View v) {
							if (TextUtils.isEmpty(task.getSignImage())) {
								ToastUtil.getInstances().showMsg("无法找到该图片~");
								return;
							}
							final String[] urls = new String[1];
							urls[0] = task.getSignImage();
							Intent intent = new Intent(v.getContext(),
									ImagePagerActivity.class);
							intent.putExtra(
									ImagePagerActivity.EXTRA_IMAGE_URLS, urls);
							intent.putExtra(
									ImagePagerActivity.EXTRA_IMAGE_INDEX, 0);
							v.getContext().startActivity(intent);
						}
					});
			holder.setOnClickListener(R.id.tvChooseMember,
					new OnClickListener() {

						@Override
						public void onClick(View v) {
							Intent intent = new Intent(v.getContext(),
									JoinMemberReadActivity.class);
							intent.putExtra("memberList",
									new Gson().toJson(task.getPartMembers()));
							startActivity(intent);
						}
					});

			if (task.getItemStatus() != 2 && task.getPartMembers() != null
					&& task.getPartMembers().size() > 0) {
				task.setItemStatus(1);
			}

			switch (task.getItemStatus()) {
			case 1:
				// 显示已参与的成员
				holder.setVisible(R.id.tvJoinMember, true);
				holder.setText(R.id.tvJoinMember, "开始检测");
				holder.setVisible(R.id.rlDetect, false);
				holder.setVisible(R.id.llMember, true);
				holder.setVisible(R.id.tvJoinMember, false);
				break;
			default:
				holder.setVisible(R.id.tvJoinMember, true);
				holder.setText(R.id.tvJoinMember, "选择参与成员");
				holder.setVisible(R.id.rlDetect, false);
				holder.setVisible(R.id.llMember, false);
				holder.setVisible(R.id.tvJoinMember, false);
				break;
			}

		}
	}

	public class FinishDelagate implements ItemViewDelegate<Task> {

		@Override
		public int getItemViewLayoutId() {
			return R.layout.item_maintenance_mytask_finish;
		}

		@Override
		public boolean isForViewType(Task item, int position) {
			return item.getStatus() == 3;
		}

		@Override
		public void convert(ViewHolder holder, final Task task, int position) {
			holder.setText(R.id.tvUnitTip, "维保单位：");
			holder.setText(R.id.tvCompany, task.getWb_company_name());
			holder.setText(R.id.tvDate, task.getTask_time());
			holder.setText(R.id.tvUsername, task.getTask_user_name());
			holder.setText(R.id.tvAssginTip, "派发对象：");
			holder.setText(R.id.tvInfo, task.getParticipants());
			holder.setOnClickListener(R.id.tvDetail, new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(v.getContext(),
							MaintenanceTaskDetailActivity.class);
					intent.putExtra("id", task.getId());
					startActivity(intent);
				}
			});
		}
	}

	/**
	 * @author: HYM
	 * @Title: doAllFinish
	 * @Description: TODO(执行全部检测完成的动作) void
	 * @date: 2017-9-11
	 */
	void doAllFinish(String id, String remark, final int position,
			final int func) {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("id", id);
		params.put("remark", remark);

		VolleyRequest.StringRequestPost(getContext(),
				WebApi.MAINTENANCE_ALL_DETECT_FINISH, "", params,
				new StringInterface(getContext()) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								EventBus.getDefault().post(
										new MaintenanceTaskListEvent(type,
												position, func));

							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
						}
					}

					@Override
					public void stringError(VolleyError error) {
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}
}
